package com.situ.blog.dao.Impl;

import com.situ.blog.dao.IBlogDao;
import com.situ.blog.pojo.enity.Blog;
import com.situ.blog.pojo.query.BlogQuery;
import com.situ.blog.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

public class BlogDaoImpl implements IBlogDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public Blog selectById(Integer id) {
        return template.queryForObject("select * from blog where id=?",
                new BeanPropertyRowMapper<>(Blog.class), id);
    }

    @Override
    public List<Blog> selectByType(BlogQuery blogQuery) {
        String sql = "select * from blog where 1=1";
        List<Object> list = new ArrayList<>();
        if (!ObjectUtils.isEmpty(blogQuery.getTypeId())) {
            sql += " and type_id=?";
            list.add(blogQuery.getTypeId());
        }
        if (!ObjectUtils.isEmpty(blogQuery.getTitle())) {
            sql += " and title like ?";
            list.add("%" + blogQuery.getTitle() + "%");
        }
        return template.query(sql, new BeanPropertyRowMapper<>(Blog.class), list.toArray());
    }
}
